<?php


namespace KukePay\Tencent\OfficialAccounts\Jssdk;


use KukePay\Tencent\AccessToken\Application;
use KukePay\Tencent\Payment\Kernel\ConfigFactory;
use KukePay\Tencent\Payment\Kernel\SignFactory;

class Factory extends \KukePay\Kernel\Factory
{
    /**
     * 配置
     * @var ConfigFactory
     */
    private $config;
    /**
     * 签名
     * @var SignFactory
     */
    private $sign;
    /**
     * @var string
     */
    private $url;
    /**
     * @var string
     */
    private $jsapi_ticket;

    public function __construct(ConfigFactory $config)
    {
        $this->config = $config;
        $this->sign = SignFactory::getInterface();
        parent::__construct();
    }

    /**
     * 获取jsapi
     * @param $url
     * @param $access_token
     * @return array|string
     */
    public function get()
    {
        $timestamp = time();

        $nonceStr = $this->sign->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=" . $this->jsapi_ticket . "&noncestr=$nonceStr&timestamp=$timestamp&url=".$this->url;

        $signature = sha1($string);

        return [
            "appId" => $this->config->getAppId(),
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $this->url,
            "signature" => $signature,
            "rawString" => $string,
        ];
    }

    /**
     * @param $jsapi_ticket
     * @return $this
     */
    public function setJsapiTicket($jsapi_ticket)
    {
        $this->jsapi_ticket = $jsapi_ticket;
        return $this;
    }

    /**
     * @param $url
     * @return $this
     */
    public function setUrl($url)
    {
        $this->url = $url;
        return $this;
    }
}